﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Twitterizer.Framework;

namespace TwitterTray
{
    public partial class UpdateStatus : Form
    {
        public UpdateStatus()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Enabled = false;

            button1.Text = "Sending Update...";
            LBLupdateStatus.Text = "Sending Update...";

            Twitter twit = new Twitter(Properties.Settings.Default.username, Properties.Settings.Default.password);

            try
            {
                twit.Update(richTextBox1.Text);
                richTextBox1.Text = "";
                LBLupdateStatus.Text = "Sent Status Succesfully! (" + DateTime.Now.ToShortTimeString() + ")";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "TwitterTray! - Send Update Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            this.Enabled = true;

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            button1.Text = "Send Update (" + richTextBox1.Text.Length + "/140)";

            if (richTextBox1.Text.Length >= 140)
            {
                richTextBox1.BackColor = Color.Red;
            }
            else if (richTextBox1.TextLength >= 120)
            {
                richTextBox1.BackColor = Color.Yellow;
            }
            else
            {
                richTextBox1.BackColor = Color.White;
            }
        }

        private void UpdateStatus_Load(object sender, EventArgs e)
        {
            this.Show();
            this.Update();
            timer1.Enabled = true;
            CheckForUpdates();
        }

        DateTime lastcheck = DateTime.Now;

        private void timer1_Tick(object sender, EventArgs e)
        {
            DateTime ThisCheck = DateTime.Now;

            TimeSpan Difference = ThisCheck - lastcheck;

            

            if(Difference.TotalMinutes >= Properties.Settings.Default.updatefreq)
            {
                CheckForUpdates();
                lastcheck = DateTime.Now;
            }

            if (UndisplayedUpdates.Count > 0)
            {
                // Show Tweet
                DisplayTweet(UndisplayedUpdates[0]);
                // Remove Tweet From Undisplay List!
                UndisplayedUpdates.Remove(UndisplayedUpdates[0]);
            }


        }

        int LastHash = 0;
        List<int> PastUpdates = new List<int> { };
        List<TwitterStatus> UndisplayedUpdates = new List<TwitterStatus> { };

        /// <summary>
        /// 
        /// Update Code is NOT working Properly...
        /// 
        /// Something is not write with the checking for new/old Tweets.
        /// 
        /// mabey add the whole tweet instead of just the hash? idk
        /// 
        /// 
        /// </summary>



        private void CheckForUpdates()
        {

            notifyIcon1.BalloonTipTitle = "Checking For Updates...";
            notifyIcon1.BalloonTipText = DateTime.Now.ToShortTimeString();

            LBLupdateStatus.Text = "Checked: " + DateTime.Now.ToShortTimeString();

            Twitter twit = new Twitter(Properties.Settings.Default.username, Properties.Settings.Default.password);

            TwitterStatusCollection tweets = twit.FriendsTimeline();

            if (tweets.GetHashCode() == LastHash)
            {
                //No New Updates, Don't Bother Doing Anything
            }
            else
            {
                //Save Hash!
                LastHash = tweets.GetHashCode();


                //There Are New Tweets, Figure out which ones!

                foreach (TwitterStatus s in tweets)
                {
                    if(PastUpdates.Contains(s.GetHashCode()))
                    {
                        //This IS Old Tweet!~ Ignore it
                    }
                    else
                    {
                        //This IS New Tweet!~ REPORT!! lol
                        PastUpdates.Add(s.GetHashCode());
                        UndisplayedUpdates.Add(s);

                    }
                }
            }

        }

        private void DisplayTweet(TwitterStatus tweet)
        {
            ////string TimeAgo = "";

            //List<string> TimeAgo = new List<string> { };

            //TimeSpan Ago = DateTime.Now - tweet.Created.ToLocalTime();

            //if (Ago.Days == 1)
            //{
            //    TimeAgo.Add(Ago.TotalDays + " day");
            //}
            //else if (Ago.Days > 1)
            //{
            //    TimeAgo.Add(Ago.TotalDays + " days");
            //}

            //if (Ago.Hours == 1)
            //{
            //    TimeAgo.Add(Ago.Hours + " hour");
            //}
            //else if (Ago.Days > 1)
            //{
            //    TimeAgo.Add(Ago.Hours + " hours");
            //}

            //if (Ago.Minutes == 1)
            //{
            //    TimeAgo.Add(Ago.Minutes + " minute");
            //}
            //else if (Ago.Minutes > 1)
            //{
            //    TimeAgo.Add(Ago.Minutes + " minutes");
            //}

            //if (Ago.Seconds == 1)
            //{
            //    TimeAgo.Add(Ago.Seconds + " second");
            //}
            //else if (Ago.TotalMinutes > 1)
            //{
            //    TimeAgo.Add(Ago.Seconds + " seconds");
            //}


            //string TimeResult = "";

            //switch (TimeAgo.Count)
            //{
            //    case 0:
            //        TimeResult = "A few seconds ago";
            //        break;

            //    case 1:
            //        TimeResult = TimeAgo[0];
            //        break;
            //    default:
            //        TimeResult = TimeAgo[0] + ", " + TimeAgo[1];
            //        break;

            //}




            string Time = "";

            if (tweet.Created.ToLocalTime().DayOfYear == DateTime.Now.DayOfYear && tweet.Created.ToLocalTime().Year == DateTime.Now.Year)
            {
                Time = tweet.Created.ToLocalTime().ToShortTimeString();
            }
            else
            {
                Time = tweet.Created.ToLocalTime().ToShortDateString() + " " + tweet.Created.ToLocalTime().ToShortTimeString();
            }
            
            notifyIcon1.BalloonTipTitle = tweet.TwitterUser.UserName + "  (" + Time + ")";
            notifyIcon1.BalloonTipText = tweet.Text;
            notifyIcon1.ShowBalloonTip(500);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void gotoMyTwitterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            
        }

        private void checkForUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CheckForUpdates();
        }

        private void writeNewUpdateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
        }

        private void UpdateStatus_StyleChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.TopLevel = false;
            }
            else
            {
                this.TopLevel = true;
            }
        }

        private void clearNewUpdatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UndisplayedUpdates.Clear();
        }
    }
}
